﻿using B.S.DataBase.Domain;
using B.S.DataBase.ErrorCode;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure.Interface;
using B.S.DataBase.Read.API.Appicant.Command.TrunMeonCommand;
using MediatR;

namespace B.S.DataBase.Read.API.Appicant.CommandHandler.TrunMeonCommandHandler
{
    public class listMeonCommandHandler : IRequestHandler<listMeonCommand, APIResult<APIPing<TrunMeon>>>
    {

        private readonly IBaseRepository<TrunMeon> baseRepository;

        public listMeonCommandHandler(IBaseRepository<TrunMeon> baseRepository)
        {
            this.baseRepository = baseRepository;
        }

        public Task<APIResult<APIPing<TrunMeon>>> Handle(listMeonCommand request, CancellationToken cancellationToken)
        {
            APIResult<APIPing<TrunMeon>> result = new APIResult<APIPing<TrunMeon>>();

            var isLeader = request.Weight;          // 假设有IsLeader属性

            result.Code = APIEnum.查询成功;
            result.Msg = APIEnum.查询成功.ToString();
            var list = baseRepository.GetAll().Result.Where(x=>x.Idester==false );

            if(isLeader==1)
            {
                list = list.Where(x => x.Name == request.UserName);

            }else if(isLeader==2)
            {
                // 领导：查询本部门所有记录
                list = list.Where(x => x.DepId == request.DepId);
            }
            else if(isLeader==0)
            {
                list = list;
            }

            if(!string.IsNullOrEmpty(request.StartDate))
            {
                list = list.Where(x => x.StartDate == request.StartDate);
            }
            if (!string.IsNullOrEmpty(request.EndDate))
            {
                list = list.Where(x => x.EndDate == request.EndDate);
            }

            if(request.Suesser!=null)
            {
                list = list.Where(x => x.Suesser == request.Suesser);
            }
            if(!string.IsNullOrEmpty(request.Name))
            {
                list = list.Where(x => x.Name.Contains(request.Name));
            }
            
            int TatoCount = list.Count();
            int Totapage = (int)Math.Ceiling(TatoCount * 1.0 / (request.PageISez));

            list = list.OrderByDescending(x=>x.Trunid).Skip(request.PageISez * (request.PageIbes - 1)).Take(request.PageISez);

            APIPing<TrunMeon> page = new APIPing<TrunMeon>();
            page.TatoCount = TatoCount;
            page.Totapage = Totapage;
            page.list = list.ToList();

            result.data = page;

            return Task.FromResult(result);


        }
    }
}
